//
//  PMineResumeTagsViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/25.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "PMineResumeTagsViewController.h"
#import "LYSpecialLabelCell.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "LYSpecialLabelCell.h"
#import "PublicCategoryElementModel.h"

@interface PMineResumeTagsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateLeftAlignedLayout, UITextFieldDelegate>
@property (nonatomic, strong) UICollectionView *collectview;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *selectDataArray;

@property (nonatomic, strong) UIView *footerView;

@property (nonatomic, strong) UITextField *textfiled;
@property (nonatomic, strong) UIButton *enterBtn;
@end

@implementation PMineResumeTagsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"特长标签";
    self.selectDataArray = [NSMutableArray arrayWithCapacity:0];
    
    [self loadData];
    [self initUI];
}
- (void)loadData {
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    if (self.type == AddOrEditTypeOfEdit) {
        NSMutableArray *tempArr = [NSMutableArray arrayWithCapacity:0];
        [tempArr addObjectsFromArray:[DataToolsControl sharedManager].allCategoryInfoModel.resumetagArray];
        for (PMineResumeTagsInfoModel *tempMpdel in self.tagsArray) {
            PublicCategoryElementModel *model = [[PublicCategoryElementModel alloc] init];
            if (([tempMpdel.tag_id integerValue] == 0)&&(tempMpdel.tag_cn && tempMpdel.tag_cn.length)) {
                model.id = tempMpdel.tag_id;
                model.name = tempMpdel.tag_cn;
                model.itemWidth = [UIToolsControl textWidth:model.name size:CGSizeMake(MAXFLOAT, 30*Scale) font:Font_14]+20*Scale;
                [tempArr addObject:model];
            }
        }
        
//        for (NSInteger i = 0; i < [DataToolsControl sharedManager].allCategoryInfoModel.resumetagArray.count; i++) {
//            PublicCategoryElementModel *model = [[DataToolsControl sharedManager].allCategoryInfoModel.resumetagArray[i] copy];
        for (NSInteger i = 0; i < tempArr.count; i++) {
            PublicCategoryElementModel *model = [tempArr[i] copy];
            model.isSelect = NO;
            model.labelid = i;
            for (PMineResumeTagsInfoModel *tempMpdel in self.tagsArray) {
                if (([tempMpdel.tag_id integerValue] == [model.id integerValue])&&(tempMpdel.tag_cn && tempMpdel.tag_cn.length)) {
                    model.isSelect = YES;
                }
                if (([tempMpdel.tag_id integerValue] == 0)&&(tempMpdel.tag_cn && tempMpdel.tag_cn.length)) {
//                    model.isSelect = YES;
                    model.addNewItem = YES;
                }
            }
            [self.dataArray addObject:model];
        }
    } else {
        for (NSInteger i = 0; i < [DataToolsControl sharedManager].allCategoryInfoModel.resumetagArray.count; i++) {
            PublicCategoryElementModel *model = [[DataToolsControl sharedManager].allCategoryInfoModel.resumetagArray[i] copy];
            model.isSelect = NO;
            model.labelid = i;
            [self.dataArray addObject:model];
        }
    }
}
- (void)initUI {
    UIButton *okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-50*Scale, HeightOfStatusBar+3*Scale, 50*Scale, 36) imageName:nil target:self action:@selector(okBtnTap) title:((self.type == AddOrEditTypeOfAdd)?@"确定":@"保存") titleColor:THEMECOLOR_OF_ORANGE];
    okBtn.titleLabel.font = Font(Font_15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:okBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UILabel *topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(30*Scale, 10*Scale, WIDTH-60*Scale, 40*Scale) text:@"最多可选5项" textColor:THEMECOLOR_OF_TEXT_333333 font:Font_14];
    [self.view addSubview:topLbl];
    
    UICollectionViewLeftAlignedLayout *leftAlignedLayout = [[UICollectionViewLeftAlignedLayout alloc] init];
    leftAlignedLayout.minimumLineSpacing = 10*Scale;//最小行间距
    leftAlignedLayout.minimumInteritemSpacing = 15*Scale; //最小列间距
    CGRect frame = CGRectMake(30*Scale, 50*Scale, WIDTH-60*Scale, 0);
    _collectview = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:leftAlignedLayout];
    _collectview.backgroundColor = COLOR_OF_WHITE;
    _collectview.showsHorizontalScrollIndicator = NO;
    _collectview.showsVerticalScrollIndicator = NO;
    _collectview.delegate = self;
    _collectview.dataSource = self;
    [_collectview registerClass:[LYSpecialLabelCell class] forCellWithReuseIdentifier:isCellID];
    [self.view addSubview:_collectview];
    
    //tooter
    [_collectview registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"SpecialLabel_footer"];
    
    self.footerView = [UIToolsControl initViewWithFrame:CGRectMake(0, 0, WIDTH, 50*Scale) backgroundColor:COLOR_OF_WHITE];
    [self.view addSubview:self.footerView];
    
    UIView *bgView = [UIToolsControl initViewWithFrame:CGRectMake(30*Scale, 0, WIDTH-60*Scale, 50*Scale) backgroundColor:COLOR_OF_WHITE];
    [self.footerView addSubview:bgView];
    [bgView borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:(BorderSideTypeTop | BorderSideTypeBottom)];
    
    self.enterBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH - 90*Scale, 10*Scale, 60*Scale, 30*Scale) imageName:nil target:self action:@selector(addBtn) title:@"贴标签" titleColor:COLOR_OF_WHITE];
    self.enterBtn.backgroundColor = THEMECOLOR_OF_GREEN;
    self.enterBtn.titleLabel.font = Font(Font_14);
    self.enterBtn.layer.cornerRadius = 5*Scale;
    self.enterBtn.layer.masksToBounds = YES;
    [self.footerView addSubview:self.enterBtn];
    
    self.textfiled = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, 0, WIDTH-140*Scale, 50*Scale) placeholder:@"标签不够？手动输入8字内标签" secureTextEntry:NO font:Font_14 padding:YES];
    self.textfiled.delegate = self;
    self.textfiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.textfiled addTarget:self action:@selector(enterText:) forControlEvents:UIControlEventEditingChanged];
    [self.footerView addSubview:self.textfiled];
    
    [self chanageCollectHeight];
}
- (void)okBtnTap {
    BOOL hasSelect = NO;
    NSString *tags = @"";
    NSMutableArray *tag_cn = [NSMutableArray arrayWithCapacity:0];
    for (PublicCategoryElementModel *model in self.dataArray) {
        if (model.isSelect) {
            hasSelect = YES;
            if ([model.id isEqualToString:@"0"]) {
                if (model.addNewItem) {
                    [tag_cn addObject:model.name];
                    [self.selectDataArray addObject:model];
                }
            } else {
                if (tags && tags.length) {
                    tags = [NSString stringWithFormat:@"%@,%@", model.id, tags];
                } else {
                    tags = model.id;
                }
                [self.selectDataArray addObject:model];
            }
        }
    }
    if (!hasSelect) {
        SVPHUDError(TagsAlertText);
        return;
    }
//    if (tags && tags.length>1) {
//        tags = [tags substringToIndex:tags.length-1];
//    }
    
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:tags forKey:@"tags"];
    [dic setObject:tag_cn forKey:@"tag_cn"];
    
    [BaseNetManager requestWithMethod:POST path:PersonMine_SaveTagsInfo_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(pMineResumeTagsViewControllerBackRefresh:)]) {
                [self.delegate pMineResumeTagsViewControllerBackRefresh:self.selectDataArray];
            }
            
            [self performSelector:@selector(delayClick) withObject:nil afterDelay:0.5];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)delayClick {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LYSpecialLabelCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:isCellID forIndexPath:indexPath];
    PublicCategoryElementModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSInteger count = 0;
    for (PublicCategoryElementModel *model in self.dataArray) {
        if(model.isSelect){
            count ++;
        }
    }
    
    PublicCategoryElementModel * model = self.dataArray[indexPath.row];
    if (count < 5) {
        model.isSelect = !model.isSelect;
        [collectionView reloadData];
    } else if (count == 5 && model.isSelect == YES) {
        model.isSelect = !model.isSelect;
        [collectionView reloadData];
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    PublicCategoryElementModel *model = self.dataArray[indexPath.row];
    return CGSizeMake(model.itemWidth, 30*Scale);
}
- (void)chanageCollectHeight {
    CGFloat height = 0;
    NSInteger count = 1;
    CGFloat width = 0;
    CGFloat maxwidth = WIDTH - 60*Scale;
    for (PublicCategoryElementModel *model in self.dataArray) {
        width = model.itemWidth+15*Scale+width;
        if (width>maxwidth && (width-15*Scale)>maxwidth ) {
            count++;
            width = model.itemWidth+15*Scale;
        }
    }
    height = (30*Scale + 10*Scale)*count+10*Scale;
    self.collectview.height = height;
    self.footerView.top = self.collectview.bottom;
}
- (void)addBtn {
    if (self.textfiled.text.length) {
        NSString *str = self.textfiled.text;
        PublicCategoryElementModel *model = [[PublicCategoryElementModel alloc] init];
        model.id = @"0";
        model.addNewItem = YES;
        model.name = str;
        model.isSelect = NO;
        model.labelid = self.dataArray.count;
        model.itemWidth = [model.name sizeOfFont:Font(Font_14) maxSize:CGSizeMake(MAXFLOAT, 30*Scale)].width + 20*Scale;
        [self.dataArray addObject:model];
        
        self.textfiled.text = @"";
        [self chanageCollectHeight];
        [self.collectview reloadData];
    }
}
- (void)enterText:(UITextField *)textFiled {
    NSString *text = textFiled.text;
    if (text.length >8) {
        self.enterBtn.userInteractionEnabled = NO;
        self.enterBtn.backgroundColor = THEMECOLOR_OF_TEXT_cccccc;
    } else {
        self.enterBtn.userInteractionEnabled = YES;
        self.enterBtn.backgroundColor = THEMECOLOR_OF_GREEN;
    }
}

@end
